package cn.hchaojie.lucene.query;

import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;

public class LuceneUtils {
	private static final String INDEX_PATH = "D:\\workspace\\workspace_stxy\\lucene-day02\\index";
	
	// 创建一个搜索查询器 IndexSearcher
	public static IndexSearcher getIndexSearcher() throws IOException {
		IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(INDEX_PATH)));
		IndexSearcher indexSearcher = new IndexSearcher(reader);	
		
		return indexSearcher;
	}
	
	// 打印搜索结果
	public static void printResult(IndexSearcher indexSearcher, TopDocs topDocs) throws IOException {
		// 处理查询结果
		ScoreDoc[] scoreDocs = topDocs.scoreDocs;
		for (ScoreDoc scoreDoc : scoreDocs) {
			// 取到当前文档
			Document doc = indexSearcher.doc(scoreDoc.doc);
			
			String format = "[%d] [%.3f] [%s] \t [%s] \t [%s] \n";
			System.out.printf(format, scoreDoc.doc, scoreDoc.score, doc.get("name"), doc.get("size"), doc.get("path"));
		}
	}
}
